package com.ttmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ttmall.common.to.es.SkuEsModel;
import com.ttmall.common.utils.R;
import com.ttmall.search.config.TtmallElasticsearchConfig;
import com.ttmall.search.constant.EsConstant;
import com.ttmall.search.feign.ProductFeignService;
import com.ttmall.search.service.MallSearchService;
import com.ttmall.search.vo.AttrResponseVO;
import com.ttmall.search.vo.SearchParam;
import com.ttmall.search.vo.SearchResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    RestHighLevelClient client;

    @Autowired
    ProductFeignService productFeignService;

    @Override
    public SearchResult search(SearchParam param) {

        SearchResult searchResult = new SearchResult();

        SearchRequest searchRequest = buildSearchRequest(param);



        try {
            SearchResponse response = client.search(searchRequest, TtmallElasticsearchConfig.COMMON_OPTIONS);

            searchResult = buildSearhResult(response , param);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return searchResult;
    }

    private SearchRequest buildSearchRequest(SearchParam param) {

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        /**
         * 查询条件
         */
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (!StringUtils.isEmpty(param.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle" , param.getKeyword()));
        }
        if (param.getCatalog3Id()  != null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId" , param.getCatalog3Id()));
        }
        if(param.getBrandId() != null && param.getBrandId().size() > 0){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId" , param.getBrandId()));
        }

        if (param.getAttrs() != null && param.getAttrs().size() > 0){

            for (String attr : param.getAttrs()) {
                BoolQueryBuilder nextBoolQuery  = QueryBuilders.boolQuery();
                // attr = 1_aa:bb
                String[] s = attr.split("_");
                String attrId = s[0]; // 属性ID
                String[] attrValues = s[1].split(":"); // 属性值
                nextBoolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrId));

                nextBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue" , attrValues));

                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nextBoolQuery, ScoreMode.None);
                boolQueryBuilder.filter(nestedQuery);
            }
        }

        if (param.getHasStock() != null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock" , param.getHasStock() == 1));
        }


        // 价格区间
        if (!StringUtils.isEmpty(param.getSkuPrice())){
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] s = param.getSkuPrice().split("_");
            if (s.length == 2){
                rangeQuery.gte(s[0]).lte(s[1]);
            }
            else if (s.length == 1){
                if (param.getSkuPrice().startsWith("_")){
                    rangeQuery.lte(s[0]);
                }

                if (param.getSkuPrice().endsWith("_")){
                    rangeQuery.gte(s[0]);
                }
            }
            boolQueryBuilder.filter(rangeQuery);
        }
        searchSourceBuilder.query(boolQueryBuilder);

        // 排序/分页/高亮
        if (!StringUtils.isEmpty(param.getSort())){
            String[] s = param.getSort().split("_");
            SortOrder sortOrder = s[1].equalsIgnoreCase("asc")? SortOrder.ASC: SortOrder.DESC;
            searchSourceBuilder.sort(s[0] , sortOrder);
        }
        // 分页
        searchSourceBuilder.from( (param.getPageNum() -1) *EsConstant.PAGE_SIZE );
        searchSourceBuilder.size(EsConstant.PAGE_SIZE);

        // 高亮
        if (!StringUtils.isEmpty(param.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            searchSourceBuilder.highlighter(highlightBuilder);
        }

        // 聚合
        // 品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        searchSourceBuilder.aggregation(brand_agg);
        // 分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg");
        catalog_agg.field("catalogId").size(50);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        searchSourceBuilder.aggregation(catalog_agg);

        // 属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");

        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");

        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));

        attr_agg.subAggregation(attr_id_agg);

        searchSourceBuilder.aggregation(attr_agg);

        String s = searchSourceBuilder.toString();
        System.out.println("dsl" +s);

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, searchSourceBuilder);
        return searchRequest;
    }

    private SearchResult buildSearhResult(SearchResponse response , SearchParam param) {

        SearchHits hits = response.getHits();
        SearchResult searchResult = new SearchResult();
        // 商品
        ArrayList<SkuEsModel> skuEsModels = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0){
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel model = JSON.parseObject(sourceAsString , SkuEsModel.class);

                if (StringUtils.isNotEmpty(param.getKeyword())){
                    String highLightTitle  = hit.getHighlightFields().get("skuTitle").getFragments()[0].toString();
                    model.setSkuTitle( highLightTitle);
                }
                skuEsModels.add(model);
            }
        }
        searchResult.setProducts(skuEsModels);
        // 聚合信息
        //属性
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");

        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();

            // 属性id
            long attrId = bucket.getKeyAsNumber().longValue();
            //属性名字
            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            String attrName = attr_name_agg.getBuckets().get(0).getKeyAsString();

            // 属性所有值
            ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            List<String> values  = attr_value_agg.getBuckets().stream().map(e -> {
                return e.getKeyAsString();
            }).collect(Collectors.toList());

            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValues(values);

            attrVos.add(attrVo);
        }

        searchResult.setAttrs(attrVos);

        // 品牌
        ArrayList<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");

        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            //id
            brandVo.setBrandId(bucket.getKeyAsNumber().longValue());
            //品牌图片
            String brandImg = ((ParsedStringTerms) (bucket.getAggregations().get("brand_img_agg"))).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);
            //品牌名
            String brandName = ((ParsedStringTerms) (bucket.getAggregations().get("brand_name_agg"))).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);
            brandVos.add(brandVo);
        }
        searchResult.setBrands(brandVos);

        //分类
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        List<SearchResult.CatalogVo> catalogs = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            catalogVo.setCatalogId(bucket.getKeyAsNumber().intValue()); // 分类ID

            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);
            catalogs.add(catalogVo);
        }
        searchResult.setCatalogs(catalogs);

        //分页
        long total = hits.getTotalHits().value;

        int pages = (int) (total/EsConstant.PAGE_SIZE);

        pages = total%EsConstant.PAGE_SIZE == 0 ? pages : pages +1;

        searchResult.setTotalPages(pages);
        searchResult.setTotal( total);
        searchResult.setPageNum(param.getPageNum());

        // 导航
        List<SearchResult.NavVo>  navVos = new ArrayList<SearchResult.NavVo>() ;

        if (param.getAttrs()!= null && param.getAttrs().size() > 0){
            navVos = param.getAttrs().stream().map( e ->{
                SearchResult.NavVo navVo = new SearchResult.NavVo();

                String[] s = e.split("_");

                navVo.setNavVal(s[1]);

                R r = productFeignService.getAttrInfo(Long.parseLong(s[0]));

                if (r.getCode() == 0) {
                    AttrResponseVO attr = r.getData("attr", new TypeReference<AttrResponseVO>() {
                    });
                    navVo.setNavName(attr.getAttrName());
                } else {
                    navVo.setNavName(s[0]);
                }

                String encode = null;
                try {
                    encode = URLEncoder.encode(e, "UTF-8");
                    encode  = encode.replace("+" , "%20"); // +  编码问题
                } catch (UnsupportedEncodingException ex) {
                    ex.printStackTrace();
                }

                String newQuery = param.get_queryString().replace("attrs=" + encode, "");

                navVo.setLink("http://search.ttmall.com/list.html?"+ newQuery);

                return navVo;
            }).collect(Collectors.toList());

            searchResult.setNavs( navVos);
        }



        return searchResult;
    }


}
